package login

import (
	"context"
	"demo/api/backend/login"
	"demo/internal/service"
	"demo/utility/gtoken"
	"github.com/gogf/gf/v2/net/ghttp"
	"github.com/jinzhu/copier"
	"strconv"
)

var (
	Login = cLogin{}
)

type cLogin struct{}

func (*cLogin) Login(ctx context.Context, req *login.LoginReq) (res *login.LoginRes, err error) {

	user, err := service.Login().PassLogin(ctx, req)
	if err != nil {
		return
	}
	userKey := strconv.Itoa(user.AccountId)
	token, err := gtoken.GetGfToken(ctx).GenTokenForUserKey(ctx, userKey, user)
	if err != nil {
		return
	}
	res = &login.LoginRes{}
	err = copier.Copy(&res, user)
	if err != nil {
		return
	}
	res.Token = token
	return
}

func (*cLogin) Logout(ctx context.Context, req *login.LogoutReq) (res *login.LogoutRes, err error) {
	r := ghttp.RequestFromCtx(ctx)
	err = gtoken.GetGfToken(ctx).Logout(r)
	return nil, err
}
